﻿using Iworld.Backstage.Framework;
using Iworld.Backstage.Framework.AdministratorService;
using Iworld.Backstage.Framework.AuthorService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Iworld.Backstage
{
    public partial class EditUserWindow : ChildWindow
    {
        public EditUserWindow()
        {
            InitializeComponent();
        }


        public AuthorExport Info
        {
            get { return (AuthorExport)GetValue(InfoProperty); }
            set { SetValue(InfoProperty, value); }
        }

   
        public static readonly DependencyProperty InfoProperty =
            DependencyProperty.Register("Info", typeof(AuthorExport), typeof(EditUserWindow), new PropertyMetadata(null, (sender, args) => {
                AuthorExport ae = (AuthorExport)args.NewValue;
                EditUserWindow me = (EditUserWindow)sender;
                me.UIAccount.Text = ae.Account;
                me.UIUsername.Text = ae.Username;
                me.UILastLoginIP.Text = ae.LastLoginIp;
                me.UILastLoginTime.Text = ae.LastLoginTime.ToLongDateString();
                me.UIStatus.SelectedIndex = (int)ae.Status;
                me.UILastLoginAddress.Text = ae.LastLoginAddress;
                me.UICreatedTime.Text = ae.CreatedTime.ToLongDateString();
            }));

        private void Edit(object sender, RoutedEventArgs e)
        {
            AuthorServiceClient asc = new AuthorServiceClient();
            asc.EditUserCompleted += asc_EditUserCompleted;
            AuthorStatus? ast = (AuthorStatus)this.UIStatus.SelectedIndex;
            asc.EditUserAsync(new EditUserImport() {
                NewPassword = string.IsNullOrWhiteSpace(UINewPassword.Password) ? null : UINewPassword.Password,
               UserId=Info.Id ,
               Token = DataManager.GetValue<AdministratorExport>(DataKey.Administrator_Info).Token,
               NewStatus = ast
            });
        }

        void asc_EditUserCompleted(object sender, EditUserCompletedEventArgs e)
        {
              if(e.Result.Success)
              {
                  Info.Status = (AuthorStatus)this.UIStatus.SelectedIndex;
                  ErrorPrompt ep = new ErrorPrompt() { Info = "修改成功"};
                  ep.Closed += (ss, args) => {
                      this.DialogResult = true;
                  };
                  ep.Show();

              }else
              {
                  new ErrorPrompt() { Info =e.Result.Error}.Show();
              }
        }

        private void Cancel(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

    }
}

